const app = getApp()
const { getBillCategory } = require('../../api/bill')
const { cache_load, cache_save, cache_remove } = require('../../lib/cache')


Page({

  data: {
    category: null,
    checked: 0
  },

  onLoad: function (options) {
    var that = this
    var filter = options.filterData ? JSON.parse(options.filterData) : []

    that._getBillCategory(options.begin, options.end, function (category) {
      // 构造列表对象
      var checked = 0
      // 初始化选中状态state
      category.forEach((obj) => {
        if (filter && filter.length > 0 && filter.includes(obj.name)) {
          obj.checked = 1
          checked++
        } else if (!filter || filter.length === 0) {
          obj.checked = 1
          checked++
        }
      })
      // console.log(category)
      that.setData({
        category: category,
        checked: checked
      })
    })
  },

  // 点击全选按钮
  onTapAll() {
    var checked = this.data.checked,
      category = this.data.category
    var allChecked = checked === category.length ? 0 : 1
    category.forEach((val) => {
      val.checked = allChecked
    })
    this.setData({
      checked: checked === category.length ? 0 : category.length,
      category: category
    })
  },

  // 点击单个checkbox
  onTapItem(e) {
    var target = e.detail.value
    var category = this.data.category, checked = 0
    category.forEach((obj) => {
      if (target.includes(obj.name)) {
        obj.checked = 1
        checked++
      } else {
        obj.checked = 0
      }
    })
    this.setData({
      category: category,
      checked: checked
    });
  },

  // 提交
  onSubmit() {
    // 如果没有选择，提示
    if (this.data.checked === 0) {
      wx.showToast({
        icon: 'none',
        title: '至少选择一个类别',
      })
      return
    }
    // 如果选择了全部，即未筛选，直接返回
    if (this.data.checked === this.data.category.length) {
      wx.navigateBack()
      return
    }
    var filterData = []
    this.data.category.forEach((obj) => {
      if (obj.checked) {
        filterData.push(obj.name)
      }
    })
    app.updatePrevPage({
      'option.type': 'filter',
      'filterData': filterData,
      'searchOrFilter': 'filter'
    })
    cache_remove(['bills', 'total'])
    wx.navigateBack()
  },

  // 查询类别
  _getBillCategory(begin, end, cb) {
    var category = cache_load('filter')
    if (category && category.length > 0) {
      typeof cb === 'function' && cb(category)
      return console.log('缓存：filter')
    }
    getBillCategory({
      begin: begin,
      end: end,
    }).then(res => {
      var list = res.list
      list.sort((a, b) => {
        return a['_id'] - b['_id']
      })
      var category = []
      list.forEach((obj) => {
        obj.category.forEach((value) => {
          category.push({ name: value, type: obj._id, checked: 0 })
        })
      })
      if (category.length > 0) {
        cache_save('filter', category, 300)
      }
      console.log('数据库：filter');
      typeof cb === 'function' && cb(category)
    })
  },
})